import React, { FC, useEffect, useState } from "react";
import moment from "moment";
import { DatePicker, message, Select, Space, Spin } from "antd";
import { CaretDownOutlined } from "@ant-design/icons";
import { fetchRequest } from "@/utils/Request";
import { useRequest } from "@umijs/hooks";
import { url } from "@/utils/url";

const { Option } = Select;
const VideoPlayBack: FC<{ deviceCode: string }> = ({ deviceCode }) => {
  // 视频实例化对象
  const [player, setPlayer] = useState<any>(null);

  const [optionDate, setOptionDate] = useState<string>(
    moment().format("YYYY-MM-DD")
  );
  // 当前播放的视频链接
  const [nowPlayerUrl, setNowPlayerUrl] = useState<string>("");

  // 选择的时间
  const [checkDate, setCheckDate] = useState<{
    beginTime: string;
    endTime: string;
  }>({
    beginTime: "00:00:00",
    endTime: "23:59:59",
  });

  const [getList, setGetList] = useState<any>([]);

  const [checkId, setCheckId] = useState<number>();

  const [requestParams, setRequestParams] = useState<any>({
    beginTime: `${optionDate} ${checkDate.beginTime}`,
    deviceCode,
    endTime: `${optionDate} ${checkDate.endTime}`,
  });

  const { loading, run } = useRequest(
    (params) => fetchRequest(url.LOOK_BACK, params),
    {
      manual: true,
      onSuccess: (data) => {
        console.log(data);

        if (data.success) {
          setGetList(data.data.data);
        } else {
          message.error(data.msg);
        }
      },
    }
  );

  const timeQuantum: any[] = [];

  const timeQuantumDate = () => {
    for (let i: number = 0; i < 24; i++) {
      timeQuantum.push({
        key: i,
        time:
          i < 9
            ? "0" + i + ":00-" + "0" + (i + 1) + ":00"
            : i === 9
            ? "0" + i + ":00-" + (i + 1) + ":00"
            : i + ":00-" + (i + 1) + ":00",
      });
    }
    timeQuantum[23].time = "23:00-23:59";
  };

  // 时间转换
  timeQuantumDate();

  const onChangeTime = (date: any, dateString: string) => {
    setOptionDate(dateString);
    setRequestParams({
      ...requestParams,
      beginTime: `${dateString} ${checkDate.beginTime}`,
      endTime: `${dateString} ${checkDate.endTime}`,
    });
  };

  const handleChange = (value: string) => {
    let timePeriod;
    if (value === "all") {
      timePeriod = {
        beginTime: "00:00:00",
        endTime: "23:59:59",
      };
    } else {
      timePeriod = {
        beginTime: value.split("-")[0] + ":00",
        endTime:
          value.split("-")[1] === "23:59"
            ? value.split("-")[1] + ":59"
            : value.split("-")[1] + ":00",
      };
    }
    setCheckDate(timePeriod);
    setRequestParams({
      ...requestParams,
      beginTime: `${optionDate} ${timePeriod.beginTime}`,
      endTime: `${optionDate} ${timePeriod.endTime}`,
    });
  };

  const playVideo = (playUrl: string, index: number) => {
    setCheckId(index);
    //当前正在播放的视频，用于判断高亮
    setNowPlayerUrl(playUrl);
    setupPlayer(playUrl);
  };

  // 调用视频组件
  function setupPlayer(playUrl: string) {
    //创建播放器，就是一些自己需要的配置项
    let defaultProps: any = {
      id: "videoPlayer",
      source: playUrl,
      //source: 'https://yunqivedio.alicdn.com/2017yq/v2/0x0/96d79d3f5400514a6883869399708e11/96d79d3f5400514a6883869399708e11.m3u8',
      // source: "rtmp://58.200.131.2:1935/livetv/hunantv",
      width: "100%",
      height: "100%",
      preload: true, //开启预加载
      isLive: true,
      controlBarVisibility: "hover", //工具栏显示的触发条件
      x5_fullscreen: true, // 视频作为背景
      showBarTime: 3000, //工具栏隐藏时间
      skinLayout: false, // 工具栏配置
    };
    // 如果是hls就可控制进度
    if (playUrl.length > 4 && playUrl.substr(0, 4) === "http") {
      // 如果存在播放器先销毁
      player && player.dispose();
      defaultProps.isLive = false;
      defaultProps.x5_fullscreen = false;
      defaultProps.skinLayout = [
        {
          name: "bigPlayButton",
          align: "blabs",
          x: 30,
          y: 80,
        },
        {
          name: "H5Loading",
          align: "cc",
        },
        {
          name: "errorDisplay",
          align: "tlabs",
          x: 0,
          y: 0,
        },
        {
          name: "infoDisplay",
        },
        {
          name: "tooltip",
          align: "blabs",
          x: 0,
          y: 56,
        },
        {
          name: "thumbnail",
        },
        {
          name: "controlBar",
          align: "blabs",
          x: 0,
          y: 0,
          children: [
            {
              name: "progress",
              align: "blabs",
              x: 0,
              y: 44,
            },
            {
              name: "playButton",
              align: "tl",
              x: 15,
              y: 12,
            },
            {
              name: "timeDisplay",
              align: "tl",
              x: 10,
              y: 7,
            },
            {
              name: "fullScreenButton",
              align: "tr",
              x: 10,
              y: 12,
            },
            {
              name: "volume",
              align: "tr",
              x: 5,
              y: 10,
            },
          ],
        },
      ];
    }
    // @ts-ignore
    new Aliplayer(defaultProps, function (aliplayer) {
      setPlayer(aliplayer);
    });
  }

  useEffect(() => {
    run(requestParams);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [requestParams]);

  useEffect(() => {
    setRequestParams({
      ...requestParams,
      deviceCode: deviceCode,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deviceCode]);

  return (
    <div className="drawerOut">
      <div className="leftDrawer">
        <h3>监控画面</h3>
        <div className="showVideo">
          <div id="videoPlayer" />
        </div>
      </div>
      <div className={"rightDrawer"}>
        <h3>查询时间段</h3>
        <div className={"right-context"}>
          <div className="litteringTime">
            {/* 日期 */}
            <Space direction="vertical">
              <DatePicker
                className="date-picker"
                defaultValue={moment()}
                format="YYYY-MM-DD"
                onChange={onChangeTime}
                suffixIcon={<CaretDownOutlined />}
                allowClear={false}
              />
            </Space>
            {/* 时间段 */}
            <Select
              defaultValue="all"
              className="select-time"
              onChange={handleChange}
              dropdownClassName="dropSelect"
            >
              <Option value="all">全部时间段</Option>
              {timeQuantum.map((item) => {
                return (
                  <Option value={item.time} key={item.key}>
                    {item.time}
                  </Option>
                );
              })}
            </Select>
          </div>
          {/* 搜索列表 */}
          <div className="contentList">
            <span
              className="example"
              style={{ display: loading ? "flex" : "none" }}
            >
              <Spin />
            </span>
            {getList?.map((item: any, index: number) => (
              <div
                key={index}
                onClick={() => playVideo(item.playUrl, index)}
                className={`contentItem ${
                  checkId === index && item.playUrl === nowPlayerUrl
                    ? "clickPlay"
                    : "noClickPlay"
                } `}
              >
                <span>
                  {moment(item.beginTime).format("HH点mm分ss秒")} -{" "}
                  {moment(item.endTime).format("HH点mm分ss秒")}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default VideoPlayBack;
